<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>测试requestIdleCallback的使用</title>
    <style>
      .playground {
        background: palevioletred;
        padding: 20px;
        margin-bottom: 10px;
      }
    </style>
  </head>
  <body>
    <!-- 
      页面中有两个按钮和一个DIV，点击第一个按钮执行一项昂贵的计算，使其长期占用主线程，当计算任务执行的时候去点击第二个按钮更改页面中 DIV 的背景颜色。
      使用 requestIdleCallback 就可以完美解决这个卡顿问题。
     -->
    <div class="playground" id="play">playground</div>
    <button id="work">start work</button>
    <button id="interaction">handle some user interaction</button>

    <script>
      var play = document.getElementById("play");
      var workBtn = document.getElementById("work");
      var interactionBtn = document.getElementById("interaction");
      var iterationCount = 88888;
      var value = 0;

      var expensiveCalculation = function (IdleDeadline) {
        while (iterationCount > 0 && IdleDeadline.timeRemaining() > 1) {
          // IdleDeadline.timeRemaining() 获取浏览器的空余时间（单位ms）
          value =
            Math.random() < 0.5 ? value + Math.random() : value + Math.random(); // 昂贵的计算任务
          iterationCount = iterationCount - 1;
        }
        requestIdleCallback(expensiveCalculation);
      };

      workBtn.addEventListener("click", function () {
        requestIdleCallback(expensiveCalculation);
      });

      interactionBtn.addEventListener("click", function () {
        play.style.background = "palegreen";
      });
    </script>
  </body>
</html>
